package java_thinking.unit_21._21_6;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;

import static java_thinking.unit_21._21_5.LaunderThrowable.launderThrowable;

/**
 * @Desc:   6-15 使用 CompletionService 使页面元素在下载完成后立即显示
 * @author: cww
 * @DateTime: 2019/6/12 9:09
 */

public abstract class Renderer {
    private final ExecutorService executor;

    public Renderer(ExecutorService executor) {
        this.executor = executor;
    }
    void renderPage(CharSequence sequence) {
        final List<ImageInfo> infoList = new ArrayList<>();
        CompletionService<ImageData> completionService = new ExecutorCompletionService<>(executor);
        for (final ImageInfo imageInfo : infoList) {
            //下载每张图片线程，并放入 ExecutorCompletionService
            //多个 ExecutorCompletionService 可以共享一个 Executor
            completionService.submit(new Callable<ImageData>() {
                @Override
                public ImageData call() throws Exception {
                    return imageInfo.downloadImage();
                }
            });
        }
        renderText(sequence);
        try {
            for (int i = 0; i < infoList.size(); i++) {
                //只要下载了一张及以上即可立即渲染出来
                Future<ImageData> future = completionService.take();
                ImageData imageData = future.get();
                renderImage(imageData);
            }
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        } catch (ExecutionException e) {
            throw launderThrowable(e.getCause());
        }
    }

    interface ImageData {
    }

    interface ImageInfo {
        ImageData downloadImage();
    }

    abstract void renderText(CharSequence s);

    abstract List<ImageInfo> scanForImageInfo(CharSequence s);

    abstract void renderImage(ImageData i);
}
